;(function(){

'use strict';
angular.module('services.omdisplay.bankATA')
	.factory('staticData',StaticData)
	.service('response',Response)
	.factory('BankAtaServer',bankAtaServer)
	.factory('stStatisticsServe',stStatisticsServe)
	.factory('stDataRequest',stDataRequest);
	/**
	 *页面的所有请求服务
	 * @param Restangular ajax请求
	 * @returns {{signTerminationQuery: signTerminationQuery, stPieQuery: stPieQuery, queryBankList: queryBankList, querySignChannel: querySignChannel, queryTradeType: queryTradeType, queryStates: queryStates}}
	 */
function stStatisticsServe(Restangular,response,staticData,CoreService) {
	return {
    //签解约数据查询
		signTerminationQuery : function(params,callback) {
			return Restangular.all('sas/OMdisplay/bankATA/signTerminationQuery').post(params).then(callback);
		},
		//签解约分省查询
		stPieQuery : function(params,callback){
			return Restangular.all('sas/OMdisplay/bankATA/stPieQuery').post(params).then(callback);
		},
		//银行总对总下拉查询
    queryBankList : function() {
	    return Restangular.one('sas/OMdisplay/bankATA/bankList').get();
    },
		//签约渠道查询
		querySignChannel : function(params) {
			params = staticData.changeData.businessCode;
			if (response.data.signChannelList && response.data.signChannelList.length !== 0) {
				return;
			}
			Restangular.all('sas/common/accessChannelsQuery').post(params).then(function(res){
				res.state === '10000' ? response.data.signChannelList = res.data : CoreService.dialog(res.state);
			});
			return response;
		},
		//交易类型查询
		queryTradeType : function(params) {
			return Restangular.all('sas/common/tradeTypeQuery').post(params);
		},
		//签解约状态查询
		queryStates : function(){
			if (response.data.businessStates && response.data.businessStates.length !== 0) {
        return;
      }
			Restangular.one('sas/OMdisplay/bankATA/businessStates').get().then(function(res){
				res.state === '10000' ? response.data.businessStates = res.data : CoreService.dialog(res.state);
			});
			return response;
		}
	};
}
stStatisticsServe.$inject = ['Restangular','response','staticData','CoreService'];

	/**
	 * 表单查询条件数据服务，用于存储数据
	 */
	function StaticData(COREDATA){
		var data ={};
		return {
			changeData:data,
			getData: getData
		};

		function getData(){
			var businessCode = {businessLine:[]};
			var businessLineData = COREDATA.BUSINESSLINE;
			angular.forEach(businessLineData, function(item){ //从业务线数组里拿出银行总对总的code参数
				if(item.businessLineName.indexOf('总对总') !== -1){
					businessCode.businessLine[0] = item.businessLineCode;
				}
			});
			//页面绑定数据
			data.translate = {
				bankCode: [],
				provinceCode: [],
				signChannelCode: [],
				signChannelName: [],
				tradeTypeCode: [],
				businessStateCode: [],
				timeTypeCode: {timeTypeCode: '1',timeTypeName: '日'},
				startTime: new Date(),
				startQuarter: { code: '1', quarterName: '第一季度'},
				endTime: new Date(),
				endQuarter: { code: '1', quarterName: '第一季度'},
				year: {}
			};
			data.flagName = {
				shoumun: {flag: 1}, //下拉块伸展判断
				flag:'table',       //图表切换判断
				close: false,       //通过点击控制下拉框的伸展
			  clickFlag: true    //通过点击图标进行的查询
			};
			data.params = { };   //分页所需参数
			data.clickForm = {};

      data.viewData = { }; //时间标题显示
		  data.tradeTypes = [
		  	{ tradeTypeCode:'01',tradeTypeName:'签约'}  //交易类型静态数据
		  ];
		  data.businessCode = businessCode;            //银行总对总业务线code
      return data;
		}
	}

	StaticData.$inject = ['COREDATA'];

	/**
	 * 请求返回数据
	 */
	function Response (){
		this.data = {
      bankList: [],
			businessStates: [],
			signChannelList: [],
			totalCount:'',
			title:{},
			totalSignNum:'',
			totalTermNum:'',
			signRateNum:'',
			signData: [],
			chartData: [],
			outData:{}
		};
		this.setData = function(){
			this.data = {
				title:{},
				outData:{}
			};
		};
	}

	function stDataRequest(staticData,BankAtaServer,stStatisticsServe,response,CoreService,CoreLoading,$filter){
		var queryInfo;
		var allData;
		var flags;
		var myEcharts;
		var termEcharts;
		var ifExsit;  //是否查询有数据 false为未查到数据
		var title;           //标题
		return {
			searchST: searchST,
			requestData:requestData,
			pageQuery: pageQuery,
			pieQuery: pieQuery,
			changeTable: changeTable,
			changeView: changeView
		};
		//根据下拉框进行查询
		function searchST(formValid){
			queryInfo = BankAtaServer.translateData(staticData.changeData.translate);
			allData = staticData.changeData;            //获取绑定的所有数据
			flags = staticData.changeData.flagName;     //获取所有判断的字段
			flags.shoumun.flag == 1 ? flags.shoumun.flag = 0:flags.shoumun.flag = 1;
			if (flags.shoumun.flag === 1 || formValid ) {
				flags.shoumun.flag = 1;
				return;
			}
			ifExsit = true;
			requestData(queryInfo);
		}

		function requestData(data) {
			var page = { currentPage: 1, pageSize: '10' };  //分页初始化的查询参数
			angular.copy(data,staticData.changeData.params);
			staticData.changeData.params.page = page;
			//每次通过requestData都会显示加载样式
			CoreLoading.setState(true);
			flags.shoumun.flag = 1;

			if(flags.flag === 'view'){
				pieQuery(data);
			}else {
				pageQuery(staticData.changeData.params);
			}
			// if(is.equal(flags.flag,'table')){
			// 	pageQuery(staticData.changeData.params);
			// }else if(is.equal(flags.flag,'view')){
			// 	pieQuery(data);
			// }
		}
		//表格点击进行查询请求
		function pageQuery(params) {
			var vparams;  //分页的请求参数
			CoreLoading.setState(true);    //点击分页按钮时会有加载样式
			//进入银行总对总页面第一次查询用的是页面的查询参数
			//以后的参数都是第一次查询有数据时的查询参数
			if(!flags.close||ifExsit){
				queryInfo.currentPage = params.page.currentPage;
				queryInfo.pageSize = params.page.pageSize;
				vparams = queryInfo;
			}else{
				allData.clickForm.currentPage = params.page.currentPage;
				allData.clickForm.pageSize = params.page.pageSize;
				vparams = allData.clickForm;
			}
			stStatisticsServe.signTerminationQuery(vparams, function(res){
				if (is.equal(res.state,'10000')) {
					flags.shoumun.flag = 0;
					CoreLoading.setState(false);
					if (is.empty(res.data)) {
						flags.shoumun.flag = 1;          //查询框展开
						flags.close = false;
						flags.flag = '';
						ifExsit = false;                 //没有查到数据时为false;
						CoreService.dialog(res.state);
					} else {
						flags.close = true;              //第一次查询到数据后选择框可以任意上下拉
						//页面表格显示数据
						response.data.signData = res.data;
						//签解约总条数，和后台发回的数据的总条数
						response.data.totalCount = res.num[0].totalCount;
						response.data.signNum = res.num[0].totalSignNum;
						response.data.terminationNum = res.num[0].totalTermNum;
						if(ifExsit){
							title = BankAtaServer.titleTimeName(queryInfo);
							response.data.title.tradeTypeName = title.tradeTypeName;
							response.data.title.titleTime = title.titleTime;//当查询到有数据时
							angular.copy(queryInfo,staticData.changeData.clickForm);
						}else{
							title = BankAtaServer.titleTimeName(staticData.changeData.clickForm);
							response.data.title.tradeTypeName = title.tradeTypeName;
							response.data.title.titleTime = title.titleTime;
						}
						flags.flag = 'table';
						exportView();
					}
				}

			});
		}
    //分省饼图查询
		function pieQuery(params){
			var stData;           //格式化的签解约饼图数据
			var allStData = {};   //用于封装签解约的数据，可以用于循环迭代
			var signData = [];
			var terminationData = [];
			var seriesName = ['分省签约占比','分省解约占比'];  //饼图标题
			CoreLoading.setState(true);                     //点击分页按钮时会有加载样式
			stStatisticsServe.stPieQuery(params,callBack);
			//请求的回调函数
			function callBack(res){
				if (res.state === '10000'&& res.data.length>0) {
					//当查询有数据时，查询框收拢，加载页面隐藏
					CoreLoading.setState(false);
					flags.shoumun.flag = 0;
					res.data = res.data.map(function(item){
						return {provinceName:item.provinceName,signRate:item.signRate,
							terminationRate:(item.terminationRate),signNum:item.signNum,terminationNum:item.terminationNum};
					});
					//构建饼图结构的签约所有数据
					signData = res.data.map(function(item){
						return {name:item.provinceName+ '\n' + item.signRate.toFixed(2) + '%',value:item.signNum};
					});
					//构建饼图结构的解约所有数据
					terminationData = res.data.map(function(item){
						return {name:item.provinceName+' \n' + item.terminationRate.toFixed(2) + '%',value:item.terminationNum};
					});

					allStData.signData = signData;
					allStData.terminationData = terminationData;

					//分省表格显示数据
					response.data.chartData = res.data;

					//将签约数据进行排序
					allStData.signData.sort(function(a,b){
						return a.value < b.value ? 1 : -1;
					});
					//将解约数据进行排序
					allStData.terminationData.sort(function(a,b){
						return a.value < b.value ? 1 : -1;
					});
					if(ifExsit){
						title = BankAtaServer.titleTimeName(params);
						response.data.title.tradeTypeName = title.tradeTypeName;
						response.data.title.titleTime = title.titleTime;//当查询到有数据时
						angular.copy(params,staticData.changeData.clickForm);
					}else{
						title = BankAtaServer.titleTimeName(staticData.changeData.clickForm);
						response.data.title.tradeTypeName = title.tradeTypeName;
						response.data.title.titleTime = title.titleTime;
					}
					var signOption = new BankAtaServer.ChartOpt(response.data.title.titleTime + seriesName[0],seriesName[0]);
					var termOption = new BankAtaServer.ChartOpt(response.data.title.titleTime + seriesName[1],seriesName[1]);

					stData = BankAtaServer.getPieData(allStData);
					response.data.signRateNum = stData.sumNum.signData;

					if(is.equal(params.tradeTypeCode,'03')){
						signOption.series[0].data = stData.signData;
						termOption.series[0].data = stData.terminationData;
					}else if(is.equal(params.tradeTypeCode,'01') ){
						signOption.series[0].data = stData.signData;
					}else{
						termOption.series[0].data = stData.terminationData;
					}
					flags.flag = 'view';
					setOption(signOption,termOption);
					exportView();
				}else{
					ifExsit = false;
					flags.close = false;
					flags.flag = '';
					CoreService.dialog(res.state);
					CoreLoading.setState(false);    //点击分页按钮时会有加载样式
				  flags.shoumun.flag = 1;
				}
			}
		}

		/**
		 * [changeTable 切换到签解约表显示 向后台发请求]
		 */

		function changeTable() {
			if(flags.flag !== 'table'){
				flags.flag = 'table';
				ifExsit = false;
				pageQuery(staticData.changeData.params);
			}
		}
		/**
		 * [changeView 切换到分省签解约图显示 向后台发请求]
		 */
		function changeView(table,view) {
			myEcharts = table;
			termEcharts = view;
			return function(){
				if(flags.flag !== 'view'){
					flags.flag = 'view';
					ifExsit = false;
					pieQuery(staticData.changeData.clickForm);
				}
			};
		}

		/**
		 * 给echarts图赋值
		 * @param signOption 签约的option对象
		 * @param termOption 解约option对象
		 */
		function setOption(signOption,termOption){
			myEcharts.clear();
			myEcharts.setOption(signOption);
			myEcharts.un(echarts.config.EVENT.HOVER);
			termEcharts.clear();
			termEcharts.setOption(termOption);
			termEcharts.un(echarts.config.EVENT.HOVER);
			exportView();
		}

		/**
		 * 导出图表的请求所需数据处理
		 */
		function exportView(){
			var base64 = [];
			if(flags.flag === 'table'){
				//不作任何处理
			}else{
				if(allData.clickForm.tradeTypeCode === '03'){
					base64.push(myEcharts.getDataURL('png').split(',')[1]);
					base64.push(termEcharts.getDataURL('png').split(',')[1]);
				}else if(allData.clickForm.tradeTypeCode === '01'){
					base64.push(myEcharts.getDataURL('png').split(',')[1]);
				}else{
					base64.push(termEcharts.getDataURL('png').split(',')[1]);
				}
			}
			allData.clickForm.base64s = base64;
			response.data.outData = JSON.stringify(allData.clickForm);
		}
	}

	stDataRequest.$inject = ['staticData','BankAtaServer','stStatisticsServe','response','CoreService','CoreLoading','$filter'];
	/**
	 * 方法集合
	 * @param $filter   过滤器
	 * @param response  通过请求后的返回数据
	 * @returns {{searchTimeInit: searchTimeInit, ChartOpt: ChartOpt, getPieData: getPieData, titleTimeName: titleTimeName, translateData: translateData}}
	 */
	function bankAtaServer($filter,response,PublicFn){
		return {
			searchTimeInit: searchTimeInit,
			ChartOpt: ChartOpt,
			getPieData: getPieData,
			titleTimeName: titleTimeName,
		  translateData: translateData
		};
		/**
		 * 通过账期从页面translate对象中取出可以发给后端的格式化日期字段，用新的对象searchInfo封装
		 * @param timeType 账期
		 * @param translate 页面绑定的查询对象
		 * @param flag      flag有值时只是根据账期赋初始化时间,没有值时进行数据格式化
		 * @returns {{}}  返回开始，结束时间
		 */
		function searchTimeInit(timeType,translate,flag){
			var startTime;
			var endTime;
			var month = new Date().getMonth();                  //当前月份
			var day = new Date().getDate();                     //当前天
			var year = new Date().getFullYear();                //当前年份
			var searchTime = { startQuarter:'',endQuarter:''};  //默认有季度字段，且为空字符串
			switch (timeType) {
				case '1':
					if(is.equal(flag,'initTime')){
						translate.startTime = new Date(year, month, day - 1);
						translate.endTime = new Date(year, month, day - 1);
					}else{
						searchTime.startTime = $filter('date')(translate.startTime,'yyyy-MM-dd');
						searchTime.endTime = $filter('date')(translate.endTime,'yyyy-MM-dd');
					}
					break;
				case '3':
					if(is.equal(flag,'initTime')){
						translate.startTime = new Date(year, month);
						translate.endTime = new Date(year, month);
					}else{
						searchTime.startTime = $filter('date')(translate.startTime,'yyyy-MM-dd');
						searchTime.endTime = $filter('date')(translate.endTime,'yyyy-MM-dd');
					}
					break;
				case '4':
					if(is.equal(flag,'initTime')){
						translate.year.startTime = '';
						translate.year.endTime = '';
					}else{
						startTime = splitTime(translate.year.startTime);
						endTime = splitTime(translate.year.endTime);
						searchTime.startTime = startTime.year+'-01-01' ;
						searchTime.endTime = endTime.year+'-01-01' ;
						searchTime.startQuarter = startTime.quarter;
						searchTime.endQuarter = endTime.quarter;
					}
					break;
				case '5':
					if(is.equal(flag,'initTime')){
						translate.year.startTime = Number(new Date().getFullYear());
						translate.year.endTime = Number(new Date().getFullYear());
					}else{
						searchTime.startTime = translate.year.startTime+'-01-01' ;
						searchTime.endTime = translate.year.endTime+'-01-01' ;
					}
			}
			return flag === 'initTime' ? translate : searchTime;
		}

		/**
		 * 季度字符串,解析为年度和季度字段
		 * @param quarterString 季度字符串
		 * @returns {{}} 返回季度，年份的对象
		 */
		function splitTime(quarterString){
			var yearQuarter ={};
			var year = quarterString.substring(0,4);
			var quarter = quarterString.substring(4,5);
			yearQuarter.year = year;
			yearQuarter.quarter = quarter;
			return yearQuarter;
		}

		/**
		 *将页面数据转换成后台需要的数据
		 */
		function translateData(translate){
	    var searchInfo = {
	    	bankCode: []
	    };
			var timeData;    //开始结束时间对象
			//绑定页面model的数据
			searchInfo.timeTypeCode= '1';
			searchInfo.bankCode.push(translate.bankCode);

			searchInfo.provinceCode = translate.provinceCode.map(function(item) {
				return item.provinceCode;
			});
			searchInfo.signChannelCode = translate.signChannelCode.map(function(item) {
				return item.channelCode;
			});
			if(searchInfo.signChannelCode.length === 0){
				searchInfo.signChannelName = '全部';
			}else{
				searchInfo.signChannelName = translate.signChannelCode.map(function(item){
					return item.channelName;
				}).join();
			}

			//业务类型多选
			searchInfo.tradeTypeCode = translate.tradeTypeCode.map(function(item){
				return item.tradeTypeCode;
			});
			if(searchInfo.tradeTypeCode.length === 0 || searchInfo.tradeTypeCode.length>1){
				searchInfo.tradeTypeCode = '01';
			}else{
				searchInfo.tradeTypeCode = searchInfo.tradeTypeCode.join(',');
			}
			searchInfo.businessStateCode = translate.businessStateCode.map(function(item) {
				return item.businessStateCode;
			});
			if(searchInfo.businessStateCode.length === 0){
				searchInfo.businessStateCode = ['00','01','02'];
			}
			//当业务类型选择解约的时候默认状态为'03'
			if( searchInfo.tradeTypeCode === '02' ){
				searchInfo.businessStateCode = ['03'];
			}
			searchInfo.timeTypeCode = translate.timeTypeCode.timeTypeCode;

			timeData = searchTimeInit(searchInfo.timeTypeCode,translate);
			searchInfo.startTime = timeData.startTime;
			searchInfo.endTime = timeData.endTime;
			searchInfo.startQuarter = timeData.startQuarter;
			searchInfo.endQuarter = timeData.endQuarter;

//			response.data.searchInfo = searchInfo;
			return searchInfo;
		}


		/**
		 * 创建echart对象
		 * @param title 饼图大标题
		 * @param subName 饼图数据内的小标题
		 */
		function ChartOpt(title,subName){
			this.title = { text:title,x:'center'};
			this.tooltip ={ trigger:'item',formatter:'{a} <br/>{b} ({c}笔) '};
			this.animation  = false;
			this.series = [
				{
					name:subName,
					type:'pie',
					center: ['50%','50%'],
					radius : '65%',
					data:[]
				}
			];
		}

		/**
		 * 将饼图数据进行处理成适合需求的数据结构
		 * @param allStData
		 * @returns {*} 包含两个饼图的数据和签约总数对象
		 */
		function getPieData(allStData){
			var sumNum = {};   //签解约总数
			angular.forEach(allStData, function(data,name){
				sumNum[name] = 0;
				angular.forEach(data, function(item,key) {
					var itemStyle = {};
					itemStyle.normal ={};
					itemStyle.normal.label = { show: false };
					itemStyle.normal.labelLine = { show: false,length:15};
					item.itemStyle = itemStyle;
					sumNum[name] += item.value;
					if(key < 8){
						item.itemStyle.normal.label.show = true;
						item.itemStyle.normal.labelLine.show = true;
						data[key] = item;
					}else{
						data[key] = item;
					}
				});
			});
			allStData.sumNum = sumNum;
			return allStData;
		}

		/**
		 * 获取标题名
		 * @param data 查询条件对象
		 * @returns {{}} 查询日期和业务类型名的对象
		 */
		function titleTimeName(data){
			var titleName = {};
			var tradeTypeName;
			var titleTime;
			var startTime = (data.startTime+'').replace(/-/g,'');
			var endTime = (data.endTime+'').replace(/-/g,'');
			var startQuarter = replaceCodeC(data.startQuarter);
			var endQuarter = replaceCodeC(data.endQuarter);

			if(data.tradeTypeCode === '03'){
				tradeTypeName = '签解约';
			}else{
				tradeTypeName = data.tradeTypeCode === '01' ? '签约': '解约';
			}
			titleTime = PublicFn.fmtDateTitle(data,'timeTypeCode');
			// switch (data.timeTypeCode) {
			// 	case '1':
			// 		if(startTime === endTime){
			// 			titleTime = startTime;
			// 		}else{
			// 			titleTime = startTime + ' 至 ' + endTime;
			// 		}
			// 		break;
			// 	case '3':
			// 		if(startTime === endTime){
			// 			titleTime = startTime.substring(0,6);
			// 		}else{
			// 			titleTime = startTime.substring(0,6) + ' 至 ' + endTime.substring(0,6);
			// 		}
			// 		break;
			// 	case '4':
			// 		if(startTime === endTime && startQuarter === endQuarter){
			// 			titleTime = startTime.substring(0,4) + startQuarter;
			// 		}else{
			// 			titleTime = startTime.substring(0,4) + startQuarter + ' 至 '+ endTime.substring(0,4)+ endQuarter;
			// 		}
			// 		break;
			// 	case '5':
			// 		if(startTime === endTime){
			// 			titleTime = endTime.substring(0,4);
			// 		}else{
			// 			titleTime = startTime.substring(0,4) + ' 至 ' + endTime.substring(0,4);
			// 		}
			// }
			titleName.tradeTypeName = tradeTypeName;
			titleName.titleTime = titleTime;

			return titleName;
		}
		/**
		 * 根据季度code转化成汉字
		 * @param quarterCode 季度code
		 * @returns {string} 当前季度字符串 '第n季度'
		 */
		function replaceCodeC(quarterCode){
			var charName = quarterCode === '1' ? '一': quarterCode === '2' ? '二' : quarterCode === '3' ? '三' : '四';
			var quarterName = '第'+charName+'季度';
			return quarterName;
		}
	}
	//银行总对总
	bankAtaServer.$inject = ['$filter','response','PublicFn'];
})();